package com.project_doctor.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.project_doctor.mapper.MessageMapper;
import com.project_doctor.pojo.Conversation;
import com.project_doctor.pojo.Doctor;
import com.project_doctor.pojo.Message;
import com.project_doctor.service.ConversationService;
import com.project_doctor.mapper.ConversationMapper;
import com.project_doctor.service.DoctorService;
import com.project_doctor.service.MessageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PathVariable;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;

/**
* @author 龙龙与贝儿
* @description 针对表【t_conversation】的数据库操作Service实现
* @createDate 2025-06-07 11:22:38
*/
@Service
public class ConversationServiceImpl extends ServiceImpl<ConversationMapper, Conversation>
    implements ConversationService{
    @Autowired
    private ConversationMapper conversationMapper;
    @Autowired
    MessageService messageService;
    @Autowired
    DoctorService doctorService;

    @Autowired
    MessageMapper messageMapper;

    @Override
    @Transactional
    public Conversation getOrCreateConversation(Long userId, Long participantId) {
        // 先查询是否存在会话
        Conversation conversation = conversationMapper.selectOne(new QueryWrapper<Conversation>()
                .eq("starter_id", userId)
                .eq("participant_id", participantId));

        if (conversation != null) {
            return conversation;
        }

        // 创建新会话
        Doctor participant = doctorService.getUserById(participantId);
        conversation = new Conversation();
        conversation.setStarterId(userId);
        conversation.setParticipantId(participantId);
        conversation.setUnreadCount(0);
        conversation.setIsReadCon(0);
        conversation.setCreateTime((new Date()));
        conversation.setUpdateTime((new Date()));


        conversationMapper.insert(conversation);
        Conversation conversation1 = conversationMapper.selectById(conversation.getId());
        return conversation1;
    }

    @Override
    public Conversation getConversationById(Long conversationId) {
        return conversationMapper.selectById(conversationId);
    }

    @Override
    public void updateConversation(Conversation conversation) {
        conversationMapper.updateById(conversation);
    }

    @Override
    @Transactional
    public void markAsRead(Long conversationId,Long id) {
        // 更新消息为已读状态
        messageService.markAsReadBatch(conversationId,id);

        // 更新对话未读计数
        UpdateWrapper<Conversation> wrapper2 = new UpdateWrapper<>();
        wrapper2.eq("id", conversationId)
                .set("unread_count", 0)
                .set("is_read_con", 1);
        conversationMapper.update(null, wrapper2);
    }

    @Override
    public List<Conversation> getAllConversations(Long userId) {
        // 查询对话列表
        List<Conversation> conversations = conversationMapper.getAllConversationsWithTwoProfile(userId);

        // 加载参与者信息
        for (Conversation conversation : conversations) {
            // 计算未读消息数
            Integer unreadCount = messageService.calculateUnreadCount(conversation.getId(), userId);
            conversation.setUnreadCount(unreadCount);

            // 获取最新消息
            Message latestMessage = messageService.getLatestMessage(conversation.getId());
            if (latestMessage != null) {
                conversation.setLatestMessageId(latestMessage.getId());
                conversation.setLatestMessage(latestMessage);
            }
        }
        return conversations;
    }

//    private int calculateUnreadCount(Long conversationId, Long userId) {
//        QueryWrapper<Message> queryWrapper = new QueryWrapper<>();
//        queryWrapper
//                .eq("conversation_id", conversationId)
//                .ne("sender_id", userId)  // 不是当前用户发送的消息
//                .eq("is_read", 0);    // 未读消息
//
//        return messageMapper.selectCount(queryWrapper).intValue();
//    }

//    private Message getLatestMessage(Long conversationId) {
//        QueryWrapper<Message> queryWrapper = new QueryWrapper<>();
//        queryWrapper
//                .eq("conversation_id", conversationId)
//                .orderByDesc("message_time")
//                .last("LIMIT 1");
//
//        return messageMapper.selectOne(queryWrapper);
//    }


    @Override
    public void updateLatestMessage(Long conversationId, Message message) {
        // 更新对话的最新消息
        Conversation conversation = this.getConversationById(message.getConversationId());
//        conversation.setUnreadCount(conversation.getUnreadCount() + 1);
        conversation.setLatestMessageId(message.getId());
        // 只有接收方才增加未读计数
        if (message.getSenderId().equals(conversation.getParticipantId())) {
            conversation.setUnreadCount(conversation.getUnreadCount() + 1);
        }
        conversation.setLatestMessage(message);
        this.updateConversation(conversation);
    }
}




